package com.adam.example.newssearches8_2_0.controller;

import com.adam.example.newssearches8_2_0.dto.SearchNewsDTO;
import com.adam.example.newssearches8_2_0.service.EsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/")
public class BaseController {

    @Autowired
    private EsService esService;

    @GetMapping("index")
    public String index() {
        return "index";
    }

    @RequestMapping("searchNews")
    public String searchNews(@RequestParam String query, @RequestParam(required = false, defaultValue = "1") int pageNo
                             , Model model) {
        Assert.isTrue(pageNo > 0, "searchNews invalid pageNo:" + pageNo);
        SearchNewsDTO searchNewsDTO = esService.searchNews(query, pageNo);
        model.addAttribute("result", searchNewsDTO);
        model.addAttribute("query", query);
        model.addAttribute("pageNo", pageNo);
        return "search";
    }

}
